package com.practice.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.practice.reggie.common.R;
import com.practice.reggie.entity.Employee;
import com.practice.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Collections;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param httpServletRequest
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest httpServletRequest, @RequestBody Employee employee){
        //首先对密码进行md5加密，防止数据库数据丢失引起信息泄露
        String password = employee.getPassword();
        String pwdMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据用户名查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());//设置查询条件
        Employee emp = employeeService.getOne(queryWrapper);
        //如果未查到
        if (emp==null){
            return R.error("登录失败，请检查账号或密码是否正确！");
        }
        //则比对密码是否相同
        if (!emp.getPassword().equals(pwdMd5)){
            return R.error("登录失败，请检查账号或密码是否正确！");
        }
        //查看用户账户状态是否禁用
        if (emp.getStatus()==0){
            return R.error("登录失败，该账号已被禁用！");
        }

        httpServletRequest.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 退出按钮
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理session中保存当前员工的信息
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 添加员工
     * @param httpServletRequest
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> addEmployee(HttpServletRequest httpServletRequest,@RequestBody Employee employee){
        log.info("新增员工，员工信息：{}",employee.toString());
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //获得当前登录用户的id（从登录时存入session的信息中取出）
        Long empId = (Long) httpServletRequest.getSession().getAttribute("employee");
        //设置创建人或修改人
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

//        try {
            employeeService.save(employee); //使用统一异常处理类，try catch捕捉异常进行注销
//        } catch (Exception e) {
//            e.printStackTrace();
//            return R.error("添加员工失败，请检查！");
//        }

        return R.success("新增员工成功！");
    }

    /**
     * 员工分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 账号禁用状态修改
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> updateStatus(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        Long eId = (Long) request.getSession().getAttribute("employee");

        //使用了统一公共字段填充，这里需要注销，不使用公共字段填充则放开这里
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(eId);

        employeeService.updateById(employee);
        return R.success("操作成功！");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if (employee!=null){
            return R.success(employee);
        }
        return R.error("没有查询到对应的员工信息！");
    }
}
